var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var debug = require('debug')('wechat-consultant');
var settings = require('./config');
var rtmessage = require('./routes/message'),
    rtgrab = require('./routes/grabsingle'),
    rtbuy = require('./routes/buy'),
    rtwcpay = require('./routes/wcpay'),
    rtrelet = require('./routes/relet'),
    rtsocket=require('./routes/socket'),
    rtpayoff = require('./routes/payoff');
var wechat = require('wechat');
var models = require("./models"),
    Message = models.Message,
    User = models.User,
    WCSession = models.WCSession;
var util_tool = require('./utils');
var util_wechat = require('./utils/wechatutil');
var _ = require('underscore');
var io=require('socket.io');
var async = require('async');
var app = express();
debug("this is path:" + __dirname);
// view engine setup
app.configure(function () {
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'ejs');
    app.use(favicon());
    app.use(logger('dev'));
    app.use(express.query());
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded());
    //app.use(cookieParser());
    // app.use(express.session({
    //     secret: "consultant",
    //     store: new MongoStore({
    //         db: settings.db_url
    //     })
    // }));
    app.use(express.static(path.join(__dirname, 'public')));

    //WXSession
    app.use(express.cookieParser());
    app.use(express.session({
         secret: 'keyboard cat',
         cookie: {
             maxAge: 15*60*6
         }
    }));
    //接收微信服务平台消息
    app.use('/wechat', wechat('EMAG44IWY8THZ39A6DMCYUIWDM0BE8').text(function (message, req, res, next) {
        debug('get message:', message);
        //响应微信服务器已经处理此条消息
        res.end("");
        //处理评价
        new util_tool().processComment(message, function (result) {
            if (result) {
                //处理消息
                new util_tool().processMessage(message);
            }else{
                // //消息存储
                new util_tool().saveMsg(message, function (err) {
                    debug("add new Message", err);
                })
            }
        })


    }).image(function (message, req, res, next) {
        // TODO
        //响应微信服务器已经处理此条消息
        res.end("");
        debug('get message:', message);
        //处理消息
        new util_tool().processMessage(message);
        // //消息存储
        /*new util_tool().saveMsg(message, function (err) {
            debug("add new Message", err);
        })*/
    }).voice(function (message, req, res, next) {
        //响应微信服务器已经处理此条消息
        res.end("");
        debug('get message:', message);
        //处理消息
        new util_tool().processMessage(message);
        // //消息存储
        new util_tool().saveMsg(message, function (err) {
            debug("add new Message", err);
        })
    }).video(function (message, req, res, next) {
        //响应微信服务器已经处理此条消息
        res.end("");
        debug('get message:', message);
        //处理消息
        new util_tool().processMessage(message);
        // //消息存储
        new util_tool().saveMsg(message, function (err) {
            debug("add new Message", err);
        })
    }).location(function (message, req, res, next) {
        // TODO
    }).link(function (message, req, res, next) {
        // TODO
    }).event(function (message, req, res, next) {
        // TODO
        //响应微信服务器已经处理此条消息
        //res.end("");
        //咨询师在线
        if ("V101_ONLINE" == message.EventKey) {
            //new util_tool().signin('online',true,message);20150310

            new util_tool().sentImgText(message,function(searchResult){
                res.reply(searchResult);
            });

        } else if (message.EventKey == settings.zxyh_close_session_key || message.EventKey == settings.zxs_close_session_key) { //结束会话
            res.end("");
            new util_tool().closeSession(message);
        }else if("V101_OFFLINE" == message.EventKey){//用户签退
            res.end("");
            new util_tool().signin('offline',true,message);
        }else {
            res.end("");
            //关注或取消关注
            if ("subscribe" == message.Event) {
                new util_tool().initattentionUser(message);
                //new util_tool().signin('online',false,message);//关注事件系统自动给用户签到
            }
        }
    }).middlewarify());
});
//请求路由
rtmessage(app);
rtgrab(app);
rtbuy(app);
rtwcpay(app);
rtrelet(app);
rtpayoff(app);
rtsocket(app);
/// catch 404 and forward to error handler

app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

app.set('port', process.env.PORT || 80);
//var server = app.listen(app.get('port'), function () {
//    debug('Express server listening on port ' + server.address().port);
//});
//var users = {};

var server = require('http').createServer(app)
    , io = io.listen(server);
var usersList = new Array();

io.sockets.on('connection', function (socket) {
    socket.on('online', function (data) {
        console.log(data.user);
//        socket.name = data.user;
        //将上线的用户名存储为 socket 对象的属性，以区分每个 socket 对象，方便后面使用
        var user={};
//        if (!users[data.user]) {
//            users[data.user] = data.user;
//        }
        //users 对象中不存在该用户名则插入该用户名
        if(usersList.length==0){
            user.openid=data.openid;
            user.room=data.room;
            user.nickname=data.user;
            usersList.push(user);
        }else{
            test(usersList,function(doc){
                if(doc==1){
                    user.openid=data.openid;
                    user.room=data.room;
                    user.nickname=data.user;
                    usersList.push(user);
                }
            });
        }
        function test(usersList,callback){
            var doc=1;
            for(var i=0;i<usersList.length;i++){
                if (usersList[i].openid==data.openid) {
                    console.log(usersList[i].openid);
                    doc=0;
                    return callback(doc);
                }
            }
            callback(doc);
        }
        if(usersList.length==1){
            var timedown=0;
            setInterval(function () {
                    checktimeout(usersList);
                    console.log(usersList.length+"================"+usersList[timedown]);
                    timedown++;
                },
                settings.timer
            );
        }
        //向所有用户广播该用户上线信息

        socket.join(data.room);
        //io.sockets.emit('online', {users: users, user: data.user});
        socket.emit(data.room, { user: data.user,headimgurl:data.headimgurl});
    });

    socket.on('over',function(data){
        new WCSession().findByOpenidandRoom(data.openid,data.room,function(err,docs){
            if(docs.length==0){
                socket.emit(data.room, {over:0,sessionuser:data.from,sessionopenid:data.openid});
            }else if(docs.length>0){
                if(docs[0].status==2){
                    socket.emit(data.room, {over:0,sessionuser:data.from,sessionopenid:data.openid});
                }else{
                    socket.emit(data.room, {over:1,sessionuser:data.from,sessionopenid:data.openid});
                    WCSession().updateStatusByOpneIdandRoom(data.openid,data.room,function(err){});
                }
            }
        });
    });
    function checktimeout(usersList) {
        var sessionDao = new WCSession();
        sessionDao.findSessionByStatus(1, function (err, sessions) {
            _.each(sessions, function (session, index, list) {
                //判断此对话是否包含了relet_date即已经续时的会话
                var checkdate;
                var timeoutdate;
                    checkdate = session.build_date;
                    timeoutdate = settings.wc_session_timeout;
//                }
                var curdate = new Date();
                var diftime = (curdate - checkdate) / 1000;
                var sendopenid=session.send_openid;
                if (diftime > settings.wc_session_timeout) { //判断对话是否超时
                    //如果会话已经超时，更新会话状态
                    if(session.room){
                        var room=session.room;
                        sessionDao.updateStatusByOpneIdandRoom(sendopenid, room,function (err) {
                                if (err) {
                                    debug("session timeout update fail", err);
                                } else {
                                    for(var i=0;i<usersList.length;i++){
                                        if(session.send_openid==usersList[i].openid){
                                            var msg1 = {
                                                sendopenid: session.send_openid,
                                                sendtextmsg: "本次服务时间为" + timeoutdate / 60 + "分钟，已经超时,会话结束。"
                                            }
                                            socket.emit(room, {over:2,obj:msg1,sessionopenid:sendopenid});
                                        }
                                    }
                                }
                            }
                        )
                    }
                }else if (settings.wc_session_timeout - diftime <= settings.notifytime) { //如果会话时间小于2分钟提醒用户
                    if (session.notify_count == 0) {
                        if(session.room){
                            var room=session.room;
                            sessionDao.updateSessionNotifyByOpendIdandRoom(sendopenid, room,function (err) {
                                    if (err) {
                                        debug("updateSessionBySessionId is fail", err);
                                    } else {
                                        for(var i=0;i<usersList.length;i++){
                                            if(sendopenid==usersList[i].openid){
                                                var msg = {
                                                    sendopenid: sendopenid,
                                                    sendtextmsg: "本次对话还有" + settings.notifytime / 60 + "分钟就要超时。"
                                                }
                                                socket.emit(room, {over:3,obj:msg,sessionopenid:sendopenid});

                                            }
                                        }
                                    }
                                }
                            )
                        }
                    }
                }
                else {
                    debug("the session is not timeout");
                }
            })
        });
    }
    socket.on('img',function(data){
        if(data.to=='all_img'){
            //向其他所有用户广播该用户发话信息
            new WCSession().findStatusByRoom(data.room, function (datas) {
                if (datas.length == 0) {
                    new WCSession({
                        send_openid: data.openid,
                        status: 0, //0-->会话已发起,1-->会话已建立,2-->会话已结束
                        start_date: new Date(),//会话发起时间
                        public_chat: 1,
                        room: data.room
                    }).addWCSession(function (doc) {
                            WCSession().findStatusByRoom(data.room, function (datas) {
                                var wcid = datas[0].id;
                                new Message({
                                    send_openid: data.openid,
                                    sendcontent: data.msg,
                                    msgtype: "img",
                                    date: Date.parse(new Date()) / 1000,
                                    wcsessionid: wcid,
                                    room: data.room
                                }).save();
                            });
                        });
                } else {
                    var wcsessionid = datas[0].id;
                    new Message({
                        send_openid: data.openid,
                        sendcontent: data.msg,
                        msgtype: "img",
                        date: Date.parse(new Date()) / 1000,
                        wcsessionid: wcsessionid,
                        room: data.room
                    }).save();
                    WCSession().updateStatusByOpneId(datas[0].send_openid, function (err) {
                    });
                }
            });
            socket.broadcast.emit(data.room, data);
        }
    });
    socket.on('voice', function (data) {
        if (data.to == 'all_voice') {
            //向其他所有用户广播该用户发话信息
            new WCSession().findStatusByRoom(data.room, function (datas) {
                if (datas.length == 0) {
                    new WCSession({
                        send_openid: data.openid,
                        status: 0, //0-->会话已发起,1-->会话已建立,2-->会话已结束
                        start_date: new Date(),//会话发起时间
                        public_chat: 1,
                        room: data.room
                    }).addWCSession(function (doc) {
                            WCSession().findStatusByRoom(data.room, function (datas) {
                                var wcid = datas[0].id;
                                new Message({
                                    send_openid: data.openid,
                                    sendcontent: data.msg,
                                    msgtype: "voice",
                                    date: Date.parse(new Date()) / 1000,
                                    wcsessionid: wcid,
                                    room: data.room
                                }).save();
                            });
                        });
                } else {
                    var wcsessionid = datas[0].id;
                    new Message({
                        send_openid: data.openid,
                        sendcontent: data.msg,
                        msgtype: "voice",
                        date: Date.parse(new Date()) / 1000,
                        wcsessionid: wcsessionid,
                        room: data.room
                    }).save();
                    WCSession().updateStatusByOpneId(datas[0].send_openid, function (err) {
                    });
                }
            });
            socket.broadcast.emit(data.room, data);
        }
    });
    socket.on('say', function (data) {

        if (data.to == 'all') {
            //向其他所有用户广播该用户发话信息
            new WCSession().findStatusByRoom(data.room,function(datas){
                if(datas.length==0){
                    new WCSession({
                        send_openid: data.openid,
                        status: 0, //0-->会话已发起,1-->会话已建立,2-->会话已结束
                        start_date: new Date(),//会话发起时间
                        public_chat:1,
                        room:data.room
                    }).addWCSession(function(doc){
                        WCSession().findStatusByRoom(data.room,function(datas){
                            var wcid=datas[0].id;
                            console.log(wcid);
                            new Message({
                                send_openid: data.openid,
                                sendcontent: data.msg,
                                msgtype: "text",
                                date: Date.parse(new Date())/1000,
                                wcsessionid: wcid,
                                room:data.room
                            }).save();
                        });
                    });
                }else{
                    var wcsessionid=datas[0].id;
                    new Message({
                        send_openid: data.openid,
                        sendcontent: data.msg,
                        msgtype: "text",
                        date: Date.parse(new Date())/1000,
                        wcsessionid: wcsessionid,
                        room:data.room
                    }).save();
                    WCSession().updateStatusByOpneId(datas[0].send_openid,function(err){});
                }
            });
            socket.broadcast.emit(data.room, data);
        } else {
            //向特定用户发送该用户发话信息
            //clients 为存储所有连接对象的数组
            var clients = io.sockets.clients();
            //遍历找到该用户
            clients.forEach(function (client) {
                if (client.name == data.to) {
                    //触发该用户客户端的 say 事件
                    client.emit('say', data);
                }
            });
        }
    });
});
server.listen(80);



module.exports = app;